package vip.xiaonuo.vein.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;
import vip.xiaonuo.core.timer.TimerTaskRunner;
import vip.xiaonuo.core.util.DateUtils;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;
import vip.xiaonuo.facedoor.modular.devicehistory.entity.DeviceHistory;
import vip.xiaonuo.facedoor.modular.devicehistory.service.DeviceHistoryService;
import vip.xiaonuo.facedoor.modular.redis.RedisKey;
import vip.xiaonuo.vein.controller.vo.QueryRecord;
import vip.xiaonuo.vein.model.ReqUtil;
import vip.xiaonuo.vein.modular.veindeviceevent.entity.VeinDeviceEvent;
import vip.xiaonuo.vein.modular.veindeviceevent.enums.VeinDeviceEventPersonTypeEnum;
import vip.xiaonuo.vein.modular.veindeviceevent.enums.VeinDeviceEventStatusEnum;
import vip.xiaonuo.vein.modular.veindeviceevent.enums.VeinDeviceEventSysTypeEnum;
import vip.xiaonuo.vein.modular.veindeviceevent.service.VeinDeviceEventService;
import vip.xiaonuo.vein.websocket.WebSocket;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class SyncRecordTask implements TimerTaskRunner {


    @Resource
    private ReqUtil reqUtil;


    @Resource
    private WebSocket webSocket;

    @Resource
    private DeviceBaseService deviceBaseService;

    @Resource
    private VeinDeviceEventService deviceEventService;

    @Resource
    private RedissonClient redissonClient;

    @Override
    public void action(String jobParams, String taskId) {
        List<DeviceBase> deviceBases = deviceBaseService.list(new LambdaQueryWrapper<DeviceBase>().eq(DeviceBase::getDeviceType, "4")
                .eq(DeviceBase::getDeviceState, "1"));
        for (DeviceBase deviceBase : deviceBases) {
            RBucket<String> bucket = redissonClient.getBucket(RedisKey.VEIN_QUERY_RECARD_LAST_TIME_PRE.concat(deviceBase.getRegistrationCode()));
            Date deviceCurrentDate;
            String endDate;
            String startDate;
            // 首次查询前5分钟
            if (!bucket.isExists()) {
                deviceCurrentDate = DateUtils.addTimeMillis(new Date(), -120000);
                endDate = DateFormatUtils.format(deviceCurrentDate, "yyyy-MM-dd HH:mm:ss");
                startDate = DateFormatUtils.format(DateUtils.addTimeMillis(deviceCurrentDate, -300000), "yyyy-MM-dd HH:mm:ss");
                // 非首次查询最大通行记录后5分钟
            } else {
                String startDateStr = bucket.get();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    deviceCurrentDate = simpleDateFormat.parse(startDateStr);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                startDate = DateFormatUtils.format(deviceCurrentDate, "yyyy-MM-dd HH:mm:ss");
                deviceCurrentDate = DateUtils.addTimeMillis(new Date(), -120000);
                endDate = DateFormatUtils.format(deviceCurrentDate, "yyyy-MM-dd HH:mm:ss");
            }
            ArrayList<String> times = new ArrayList<>();
            times.add(startDate);
            times.add(endDate);
            QueryRecord queryRecord = new QueryRecord();
            QueryRecord.QueryCommandDTO queryCommandDTO = new QueryRecord.QueryCommandDTO();
            queryCommandDTO.setTime(times);
            queryRecord.setQueryCommand(queryCommandDTO);
            String reqSeriNo = reqUtil.getReqSeriNo(queryRecord);
            String req = reqSeriNo.concat(JSON.toJSONString(queryRecord));
            VeinDeviceEvent veinDeviceEvent = new VeinDeviceEvent()
                    .setBody(deviceBase.getId().toString().concat("_").concat(endDate))
                    .setRequest(req)
                    .setStatus(VeinDeviceEventStatusEnum.EXECUTE.getCode())
                    .setSerialNumber(reqSeriNo)
                    .setType(VeinDeviceEventPersonTypeEnum.REQUEST_RECORD.getCode())
                    .setSysType(VeinDeviceEventSysTypeEnum.DEVICE.getCode())
                    .setDeviceId(deviceBase.getId());
            deviceEventService.save(veinDeviceEvent);
            log.info("【{}】通行记录查询【{}】", deviceBase.getName(), req);
            webSocket.sendOneMessage(deviceBase.getRegistrationCode(), req);
        }
    }

    @Override
    public void executeXxlJob() throws InterruptedException {

    }
}
